package com.songmao.pricecloudapitest.utils;


import com.songmao.pricecloudapitest.db.DBMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.testng.annotations.DataProvider;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Remy
 * @description : 测试驱动类
 * @date 2020-04-03 20:49
 */
@Component
public class TestData {


    private static DBMapper mapper;

    @Autowired
    public void setMapper(DBMapper mapper) {
        TestData.mapper = mapper;
    }


    @DataProvider
    public Object[][] dataProvider(Method method) {
        return getTestData(method);
    }


    @DataProvider
    public Object[][] dataProviderMap(Method method) {
        return getTestDataMap(method);
    }


        /**
         * @description: 取出数据,放入二位数组中，最终是一个数组的形式
         * @return: Object[][]
         * @author: Remy
         * @time: 2020/4/21 12:26
         */    
    private Object[][] getTestData(Method method) {
        //获取运行对象的类名
        String className = method.getDeclaringClass().getSimpleName();
        //获取运行对象的方法名;
        String methodName = method.getName();

        //拿到对象数据
        List<Map<String, String>> list = mapper.get(className, methodName);

        //
        Object[][] objects = new Object[list.size()][];

        if (list.size() == 0) {
            return null;
        } else {
            //循环list内的Map
            for (int i = 0; i < list.size(); i++) {
                //将其Map循环取出
                Map<String, String> listMap = list.get(i);
                //定义Object数组,后续将其Map转化成Map
                Object[] obj = new Object[listMap.size()];

                Iterator<Map.Entry<String, String>> it = listMap.entrySet().iterator();
                int j = 0;
                while (it.hasNext()) {
                    Map.Entry<String, String> entrty = it.next();
                    obj[j] = entrty.getValue();
                    j++;
                }
                objects[i] = obj;
            }
        }
        return objects;
    }

        /**
         * @description:  取出数据,放入二位数组中，最终是一个Map的形式
         * @return: Object[][]
         * @author: Remy
         * @time: 2020/4/21 12:27
         */
    private Object[][] getTestDataMap(Method method) {
        //获取运行对象的类名
        String className = method.getDeclaringClass().getSimpleName();
        //获取运行对象的方法名;
        String methodName = method.getName();

        //拿到全部数据对象,数据对象全部存储在Map内;
        List<Map<String, String>> list = mapper.get(className, methodName);
        //定义二维数组，长度为上面取出的全部对象的长度
        Object[][] objects = new Object[list.size()][];

        for (int i = 0; i < list.size(); i++) {
            //进行循环,依次取出每一个数据对象,数据对象的格式是Map;然后将其放入Object[]内;
            objects[i] = new Object[]{list.get(i)};
        }
        return objects;
    }

}
